package com.itzhanghada.rebitmq.config;

import com.itzhanghada.rebitmq.aspect.RebitTransactionAspect;
import com.itzhanghada.rebitmq.compensation.CompensationService;
import com.itzhanghada.rebitmq.mq.MessageConsumer;
import com.itzhanghada.rebitmq.mq.MessageSender;
import com.itzhanghada.rebitmq.redis.RedisStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@ConditionalOnProperty(prefix = "rebit.mq", name = "enabled", havingValue = "true")
@EnableScheduling
@EnableAspectJAutoProxy
@Slf4j
public class RebitMqAutoConfiguration {
    
    @Bean
    @ConditionalOnMissingBean
    public RedisStorageService redisStorageService() {
        return new RedisStorageService();
    }
    
    @Bean
    @ConditionalOnMissingBean
    public MessageSender messageSender() {
        return new MessageSender();
    }
    
    @Bean
    @ConditionalOnMissingBean
    public CompensationService compensationService() {
        return new CompensationService();
    }
    
    @Bean
    @ConditionalOnMissingBean
    public RebitTransactionAspect rebitTransactionAspect() {
        return new RebitTransactionAspect();
    }
    
    @Bean
    @ConditionalOnMissingBean
    public MessageConsumer messageConsumer() {
        return new MessageConsumer();
    }
    
    // 配置RabbitTemplate
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMandatory(true);
        
        // 设置确认回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.debug("Message confirmed, correlationData: {}", correlationData);
            } else {
                log.error("Message confirmation failed, cause: {}", cause);
            }
        });
        
        // 设置返回回调
        rabbitTemplate.setReturnsCallback(returned -> {
            log.error("Message returned, replyCode: {}, replyText: {}",
                        returned.getReplyCode(), returned.getReplyText());
        });
        
        return rabbitTemplate;
    }
}